/**
 * Created with IntelliJ IDEA.
 * Description:排序算法
 * User: LianBao
 * Date: 2024-04-14
 * Time: 19:46
 */
public class Sort {
    /**
     * 插入排序
     */
    public void InsertSort(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int j = i - 1;
            int val = a[i];
            while (j >= 0) {
                if (val > a[j]) {
                    a[j + 1] = val;
                    break;
                } else {
                    a[j + 1] = a[j];
                }
                j--;
            }
            a[j + 1] = val;
        }
    }

    //希尔排序
    public void ShellSort(int[] a) {
        int gap = a.length;
        while (gap > 1) {
            gap /= 2;
            shell(a, gap);
        }
    }

    private void shell(int[] a, int gap) {
        for (int i = gap; i < a.length; i++) {
            int j = i - gap;
            int val = a[i];
            while (j >= 0) {
                if (val > a[j]) {
                    a[j + gap] = val;
                    break;
                } else {
                    a[j + gap] = a[j];
                }
                j -= gap;
            }
            a[j + gap] = val;
        }
    }

    //堆排序,降序建大堆
    public void HeapSort(int[] a) {
        CreateBigHeap(a);//
        int end = a.length - 1;//最后一个元素
        while (end > 0) {
            swap(a, 0, end);
            ShiftDown(a, 0, end);
            //ShiftDown的逻辑是child < end,所以不会对end位置的值调整
            end--;
        }
    }

    //建大堆
    private void CreateBigHeap(int[] a) {
        for (int parent = (a.length - 1 - 1) / 2; parent >= 0; parent--) {
            ShiftDown(a, parent, a.length);
        }
    }

    //向下调整
    private void ShiftDown(int[] a, int parent, int end) {
        int child = parent * 2 + 1;
        while (child < end) {
            if (child + 1 < end && a[child] < a[child + 1]) {
                child++;
            }
            if (a[child] > a[parent]) {
                swap(a, parent, child);//交换
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;//已经是大堆了,就不用调整了结束循环
            }
        }
    }

    private void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }

}
